﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using FacebookWrapper.ObjectModel;

namespace Desktop_Facebook
{
    internal partial class mainForm : Form
    {
        private const string k_LoggedIn = "Logged in";
        private const string k_LoggedOut = "Logged out";
		private const bool v_Checked = true;

		private FriendScoreGenerator FriendScoreGenerator { get; set; }

		private BirthdayHolder BirthdayHolder { get; set; }
		
        private CSVSerializer CSVSerializer { get; set; }

        public mainForm()
        {
            InitializeComponent();
			
			FriendScoreGenerator = new FriendScoreGenerator();
			BirthdayHolder = new BirthdayHolder();
			CSVSerializer = new CSVSerializer();
			Session.Instance.LoggedIn += new LoginEventHandler(Session_LoggedIn);
        }

        private void Session_LoggedIn(object sender, LoginEventArgs e)
        {
            if (string.IsNullOrEmpty(e.Result.ErrorMessage) && Session.Instance.LoggedInUser.Id != null)
            {
				tabControl.Enabled = true;
				buttonLogin.Enabled = false;
				pictureBoxUser.LoadAsync(Session.Instance.LoggedInUser.PictureSqaureURL);
				labelAccountName.Text = Session.Instance.LoggedInUser.Name;
				labelFriendsNumber.Text = Session.Instance.LoggedInUser.Friends.Count.ToString();
				labelThreadNumber.Text = Session.Instance.LoggedInUser.InboxThreads.Count.ToString();
				labelEventsNumber.Text = Session.Instance.LoggedInUser.Events.Count.ToString();
			}
            else
            {
				if (string.IsNullOrEmpty(e.Result.ErrorMessage))
				{
					MessageBox.Show(e.Result.ErrorMessage);
				}
				else 
				{
					MessageBox.Show("Unknown error.");
				}
            }
        }

        private void toggleAllRows(DataGridView i_DataGridView)
        {
            foreach (DataGridViewRow row in i_DataGridView.Rows)
            {
				row.Cells[1].Value = !(bool)row.Cells[1].Value;
            }
        }

        private void buttonSelectAllMessages_Click(object sender, EventArgs e)
        {
            toggleAllRows(gridViewMessages);
        }

        private void buttonBirthdaysSelectAll_Click(object sender, EventArgs e)
        {
            toggleAllRows(gridViewBirthdays);
        }

        private void buttonEventsSelectAll_Click(object sender, EventArgs e)
        {
            toggleAllRows(gridViewEvents);
        }

        private void buttonLogin_Click(object sender, EventArgs e)
        {
			Session.Instance.Login();
        }

        private void buttonLogout_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void buttonGetEvents_Click(object sender, EventArgs e)
        {
			buttonGetEvents.Enabled = false;

			foreach (Event currentEvent in Session.Instance.LoggedInUser.Events)
            {
				gridViewEvents.Rows.Add(currentEvent, !v_Checked, currentEvent.StartTime, currentEvent.Name, currentEvent.Owner.Name, currentEvent.Location);
            }

			buttonSaveEventsToCSV.Enabled = true;
		}
        
        private void buttonGetBirthdays_Click(object sender, EventArgs e)
        {
			buttonGetBirthdays.Enabled = false;

			BirthdayHolder.MakeBirthdays();
			foreach (User currentFriend in Session.Instance.LoggedInUser.Friends)
			{
				if (BirthdayHolder.Birthdays.ContainsKey(currentFriend.Id))
				{
					gridViewBirthdays.Rows.Add(currentFriend, !v_Checked, currentFriend.Name, BirthdayHolder.Birthdays[currentFriend.Id]);
				}
			}

			buttonSaveBirthdaysToCSV.Enabled = true;
        }

		private void buttonGetInbox_Click(object sender, EventArgs e)
		{
			buttonGetInbox.Enabled = false;
			List<FacebookWrapper.ObjectModel.Message> filter = new MessageFilterer().AllMessages();
			populateInboxGridView(filter);
			buttonSaveMessagesToFile.Enabled = true;
		}

		private void populateInboxGridView(List<FacebookWrapper.ObjectModel.Message> i_Messages)
		{
			gridViewMessages.Rows.Clear();
			foreach (FacebookWrapper.ObjectModel.Message currentMessage in i_Messages)
			{
                if (currentMessage.From != null)
                {
                    gridViewMessages.Rows.Add(currentMessage, !v_Checked, currentMessage.From.Name, currentMessage.Text, currentMessage.CreatedTime);
                }
			}
		}

        private void birthdayGridView_SelectionChanged(object sender, EventArgs e)
        {
            DataGridView dg = sender as DataGridView;
            User selection = dg.CurrentRow.Cells[0].Value as User;
            
            labelSelectedFriend.Text = selection.Name;
            pictureBoxFriend.LoadAsync(selection.PictureNormalURL);
        }

		private void messagesGridView_SelectionChanged(object sender, EventArgs e)
		{
			FacebookWrapper.ObjectModel.Message selection = gridViewMessages.CurrentRow.Cells[0].Value as FacebookWrapper.ObjectModel.Message;
			richTextBoxSelectionBody.Text = selection.Text;
		}

		private void buttonFilterByText_Click(object sender, EventArgs e)
		{
			List<FacebookWrapper.ObjectModel.Message> filter = 
				new MessageFilterer { Keyword = textBoxTextFilter.Text } . FilterByText();

			populateInboxGridView(filter);
		}

		private void buttonFilterByDates_Click(object sender, EventArgs e)
		{
			List<FacebookWrapper.ObjectModel.Message> filter = new MessageFilterer { Begin = dateTimePickerFrom.Value, End = dateTimePickerTo.Value } .FilterByDates();

			populateInboxGridView(filter);
		}

		private void buttonGenerateFriendInteractionStatistics_Click(object sender, EventArgs e)
		{
			gridViewInteractionStatistics.Rows.Clear();
			FriendScoreGenerator.GenerateScores();
			foreach (User currentFriend in Session.Instance.LoggedInUser.Friends)
			{
				gridViewInteractionStatistics.Rows.Add(currentFriend, currentFriend.Name, FriendScoreGenerator.Scores[currentFriend.Id].Score);
			}
		}

		private void gridViewInteractionStatistics_SelectionChanged(object sender, EventArgs e)
		{
			User friend = gridViewInteractionStatistics.CurrentRow.Cells[0].Value as User;

			labelWallPostNum.Text = FriendScoreGenerator.Scores[friend.Id].NumberOfWallPosts.ToString();
			labelMessagesNum.Text = FriendScoreGenerator.Scores[friend.Id].NumberOfMessages.ToString();
			labelLikes.Text = FriendScoreGenerator.Scores[friend.Id].NumberOfLikes.ToString();
		}

		private void buttonSaveEventsToCSV_Click(object sender, EventArgs e)
		{
			List<Event> eventsToSave = new List<Event>();
			foreach (DataGridViewRow row in gridViewEvents.Rows)
			{
				if ((bool)row.Cells[1].Value == true)
				{
					Event ev = row.Cells[0].Value as Event;
					if (ev != null) 
					{ 
						eventsToSave.Add(ev); 
					}
				}
			}

			saveFileDialog.FileName = @"Events.csv";
			saveFileDialog.ShowDialog();
			using (FileStream saveFile = new FileStream(saveFileDialog.FileName, FileMode.Create, FileAccess.Write))
			{
				CSVSerializer.Serialize(saveFile, eventsToSave);
			}
		}

		private void buttonSaveBirthdaysToCSV_Click(object sender, EventArgs e)
		{
			Dictionary<string, CustomDate> birthdaysToSave = new Dictionary<string, CustomDate>();
			
            foreach (DataGridViewRow row in gridViewBirthdays.Rows)
			{
				if ((bool)row.Cells[1].Value == true)
				{
					User friend = row.Cells[0].Value as User;
					birthdaysToSave.Add(friend.Id, BirthdayHolder.Birthdays[friend.Id]);
				}
			}
			
			saveFileDialog.FileName = @"Birthdays.csv";
			saveFileDialog.ShowDialog();
			using (FileStream saveFile = new FileStream(saveFileDialog.FileName, FileMode.Create, FileAccess.Write))
			{
				CSVSerializer.Serialize(saveFile, birthdaysToSave);
			}
		}

		private void buttonSaveMessagesToFile_Click(object sender, EventArgs e)
		{
			List<FacebookWrapper.ObjectModel.Message> messagesToSave = new List<FacebookWrapper.ObjectModel.Message>();

			foreach (DataGridViewRow row in gridViewMessages.Rows)
			{
				if ((bool)row.Cells[1].Value == true)
				{
					FacebookWrapper.ObjectModel.Message message = row.Cells[0].Value as FacebookWrapper.ObjectModel.Message;
					messagesToSave.Add(message);
				}
			}

			saveFileDialog.FileName = @"Messages.csv";
			saveFileDialog.ShowDialog();
			using (FileStream saveFile = new FileStream(saveFileDialog.FileName, FileMode.Create, FileAccess.Write))
			{
				CSVSerializer.Serialize(saveFile, messagesToSave);
			}
		}
    }
}
